//
//  MD5Util.m
//  AICommonCore
//
//  Created by 赵梁 on 2016/9/30.
//  Copyright © 2016年 zhaoliang. All rights reserved.
//

#import "MD5Util.h"

#import <CommonCrypto/CommonDigest.h>

@implementation MD5Util

+ (NSString *)md5:(NSString *)input
{
    const char *original_str = [input UTF8String];
    unsigned char outputData[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), outputData);
    
    NSMutableString *hash = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [hash appendFormat:@"%02X", outputData[i]];
    }
    return [hash lowercaseString];
}

+ (NSString *)md5ByFile:(NSString *)filepath
{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filepath];
    if (handle == nil) {
        return nil;
    }
    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    
    BOOL done = NO;
    while(!done)
    {
        NSData* fileData = [handle readDataOfLength:1024];
        CC_MD5_Update(&md5, [fileData bytes], (int)[fileData length]);
        if( [fileData length] == 0 )
            done = YES;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    
    [handle closeFile];
    NSMutableString* md5Hash = [NSMutableString string];
    for(int i=0;i<CC_MD5_DIGEST_LENGTH;i++){
        [md5Hash appendFormat:@"%02x",digest[i]];
    }
    
    return [md5Hash lowercaseString];
}


@end
